/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Block;

import DAO.AccountDAO;
import DAO.AccountLevelDAO;
import DAO.ConnectDatabase;
import Helper.AccountHelper;
import Helper.AccountLevelHelper;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import org.json.JSONObject;

/**
 *
 * @author KIENLT
 */
public class ChatForm extends javax.swing.JPanel {

    private String accountId;
    private String accountName;
    private Socket s;

    /**
     * Creates new form ChatForm
     */
    public ChatForm() {
        initComponents();
        loadAccountList();      
    }

    public ChatForm(String accountId) {
        this.accountId = accountId;
        initComponents();
        loadAccountList();
        listenerResponse lr = new listenerResponse();
        lr.start();
    }

    private void loadAccountList() {
        try {
            DefaultListModel m1 = new DefaultListModel();
            ResultSet rs = AccountDAO.FillAll(ConnectDatabase.ConnectionDatabase());
            while (rs.next()) {
                String strId = rs.getString("AccountId");
                String strName = rs.getString("FullName");
                m1.addElement(new AccountHelper(strId, strName));
            }
            lstAccount.setModel(m1);
        } catch (Exception ex) {
            Logger.getLogger(ChatForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstAccount = new javax.swing.JList();
        cbxDepartment = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        txtSearch = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtShowMessage = new javax.swing.JTextArea();
        txtMessage = new javax.swing.JTextField();
        btnSend = new javax.swing.JButton();
        lblFullName = new javax.swing.JLabel();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        lstAccount.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lstAccountMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(lstAccount);

        jLabel1.setText("Search");

        txtShowMessage.setColumns(20);
        txtShowMessage.setLineWrap(true);
        txtShowMessage.setRows(5);
        txtShowMessage.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        jScrollPane2.setViewportView(txtShowMessage);

        btnSend.setText("Send");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(cbxDepartment, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 488, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtMessage)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSend))
                    .addComponent(lblFullName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblFullName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE)
                    .addComponent(jScrollPane2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cbxDepartment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtMessage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnSend, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void lstAccountMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstAccountMouseClicked
        // TODO add your handling code here:
        lblFullName.setText(String.valueOf(lstAccount.getSelectedValue()));
    }//GEN-LAST:event_lstAccountMouseClicked

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        try {
            // TODO add your handling code here:
            OutputStream os = getS().getOutputStream();

            JSONObject json = new JSONObject();
            json.put("command", "");
            json.put("from", getFullName());
            json.put("msg", txtMessage.getText());
            json.put("to", String.valueOf(lstAccount.getSelectedValue()));
            PrintWriter pw = new PrintWriter(os, true);
            pw.println(json.toString());
        } catch (UnknownHostException ex) {
            Logger.getLogger(ChatForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ChatForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnSendActionPerformed

    private String getFullName() {
        AccountHelper accountData = new AccountHelper();
        accountData.setAccountId(accountId);
        Connection cnn = ConnectDatabase.ConnectionDatabase();
        try {
            ResultSet rs = AccountDAO.FillOne(cnn, accountData);
            if (rs.next()) {
                setAccountName(rs.getString("FullName"));
            }
        } catch (Exception ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        return getAccountName();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSend;
    private javax.swing.JComboBox cbxDepartment;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblFullName;
    private javax.swing.JList lstAccount;
    private javax.swing.JTextField txtMessage;
    private javax.swing.JTextField txtSearch;
    private javax.swing.JTextArea txtShowMessage;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the accountName
     */
    public String getAccountName() {
        return accountName;
    }

    /**
     * @param accountName the accountName to set
     */
    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    /**
     * @return the s
     */
    public Socket getS() {
        return s;
    }

    /**
     * @param s the s to set
     */
    public void setS(Socket s) {
        this.s = s;
    }
    
    class listenerResponse extends Thread {

        @Override
        public void run() {
            String msg = "";
            BufferedReader br = null;
            while (true) {
                if (s != null) {
                    try {                        
                        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                        msg = br.readLine();
                        txtShowMessage.append(msg + "\n");
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ChatForm.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(ChatForm.class.getName()).log(Level.SEVERE, null, ex);
                        try {
                            s.close();
                        } catch (IOException ex1) {
                            Logger.getLogger(ChatForm.class.getName()).log(Level.SEVERE, null, ex1);
                        }
                    }
                }
            }
        }
    }
}
